package com.street.service.impl;

import com.street.dto.DishDTO;
import com.street.entity.Dish;
import com.street.entity.DishFlavor;
import com.street.mapper.DishMapper;
import com.street.mapper.FlavorMapper;
import com.street.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    DishMapper dishMapper;
    @Autowired
    FlavorMapper flavorMapper;

    @Override
    public List<Dish> listDish(Integer shopId) {
        List<Dish> dishList = dishMapper.selectByShopId(shopId);
        for (Dish dish : dishList) {
            List<DishFlavor>flavors=flavorMapper.selectByDishId(dish.getId());
            dish.setFlavors(flavors);
        }
        return dishList;
    }

    @Override
    @Transactional
    public void insert(DishDTO dto) {
        //分两个步骤
        //1.新增一个菜品

        Dish dish = new Dish();
        //属性拷贝
        BeanUtils.copyProperties(dto,dish);
        dishMapper.insert(dish);
        //insert之后让数据库返回了insert之后的dish主键id
        //2.新增多个该菜品的口味
        List <DishFlavor> flavors = dto.getFlavors();
        if(flavors!=null&&flavors.size()>0)
            flavorMapper.insert(flavors,dish.getId());
    }

    @Override
    @Transactional
    public void update(DishDTO dto) {
        Dish dish =new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.update(dish);
        //先把原来的口味删除，再新加进去现在的口味
        flavorMapper.deleteByDishId(dish.getId());
        List<DishFlavor> flavors=dish.getFlavors();
        if(flavors!=null&&flavors.size()>0)
            flavorMapper.insert(flavors, dish.getId());
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        dishMapper.deleteById(id);
        flavorMapper.deleteByDishId(id);
    }

    @Override
    public void EnableOrUnableStatus(Integer status, Integer dishId) {
        dishMapper.updateStatus(status,dishId);
    }
}
